// PDF.js initialization
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

let pdfDoc = null,
pageRendering = false,
pageNumPending = null,
pagesContainer = document.querySelector('.pages-container'),
ctx = null,
isFullscreen = false,
touchStartX = null,
touchStartY = null,
renderedPages = new Map(), // 存储已渲染的页面
currentScrollPage = 1;

// 计算最佳缩放比例
function getOptimalScale(page) {
    const viewport = page.getViewport({ scale: 1.0 });
    const container = document.querySelector('.pdf-container');
    let containerWidth;

    if (isFullscreen) {
        // 全屏模式下的缩放逻辑
        if (window.innerWidth > window.innerHeight) {
            // 横屏模式：以高度为基准，保持一定边距
            const targetHeight = window.innerHeight - 40;
            return (targetHeight / viewport.height);
        } else {
            // 竖屏模式：以宽度为基准，最大化利用屏幕宽度
            containerWidth = window.innerWidth - 20;
            return containerWidth / viewport.width;
        }
    } else {
        // 非全屏模式：以容器宽度为基准
        containerWidth = container.clientWidth - 40;
        return containerWidth / viewport.width;
    }
}

// 检测是否为移动设备
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

// 检查元素是否在视口中
function isElementInViewport(el) {
    const rect = el.getBoundingClientRect();
    const windowHeight = window.innerHeight || document.documentElement.clientHeight;
    const windowWidth = window.innerWidth || document.documentElement.clientWidth;

    // 元素中心点在视口中即认为是当前页
    const elementCenter = rect.top + rect.height / 2;
    return elementCenter >= 0 && elementCenter <= windowHeight;
}

// 更新页码显示
function updateCurrentPage() {
    const pages = document.querySelectorAll('.pdf-page-container');
    pages.forEach(page => {
        if (isElementInViewport(page)) {
            const pageNum = parseInt(page.id.replace('page-', ''));
            if (pageNum !== currentScrollPage) {
                currentScrollPage = pageNum;
                document.getElementById('page_num').textContent = pageNum;
            }
        }
    });
}

// 使用 Intersection Observer 监听页面可见性
const pageObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const pageNum = parseInt(entry.target.id.replace('page-', ''));
            currentScrollPage = pageNum;
            document.getElementById('page_num').textContent = pageNum;
        }
    });
}, {
    root: pagesContainer,
    threshold: 0.5 // 当页面显示50%时触发
});

// 创建连续页面容器
pagesContainer.className = 'pages-container';

async function renderAllPages() {
    const container = pagesContainer;
    container.innerHTML = ''; // 清空容器

    // 创建加载指示器
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.textContent = 'Loading pages...';
    container.appendChild(loadingIndicator);

    try {
        for (let pageNum = 1; pageNum <= pdfDoc.numPages; pageNum++) {
            const pageContainer = document.createElement('div');
            pageContainer.className = 'pdf-page-container';
            pageContainer.id = `page-${pageNum}`;

            const pageCanvas = document.createElement('canvas');
            pageCanvas.className = 'pdf-page';
            pageContainer.appendChild(pageCanvas);
            container.appendChild(pageContainer);

            // 添加Intersection Observer监听
            pageObserver.observe(pageContainer);

            const page = await pdfDoc.getPage(pageNum);
            const scale = getOptimalScale(page);
            const viewport = page.getViewport({ scale });

            pageCanvas.height = viewport.height;
            pageCanvas.width = viewport.width;

            await page.render({
                canvasContext: pageCanvas.getContext('2d'),
                viewport: viewport
            }).promise;
        }
    } finally {
        loadingIndicator.remove();
        // 初始化完成后更新一次页码
        updateCurrentPage();
    }
}

// 监听滚动事件
pagesContainer.addEventListener('scroll', () => {
    requestAnimationFrame(updateCurrentPage);
});

// 监听窗口大小变化
window.addEventListener('resize', () => {
    requestAnimationFrame(updateCurrentPage);
});

// 在离开页面时清理Observer
window.addEventListener('unload', () => {
    pageObserver.disconnect();
});

// 更新全屏按钮状态
function updateFullscreenButton(isFullscreen) {
    const fullscreenBtn = document.getElementById('fullscreen');
    if (isFullscreen) {
        fullscreenBtn.innerHTML = `<i class="fas fa-compress"></i>${isMobile ? '' : ' <span class="d-none d-sm-inline">Exit</span>'}`;
    } else {
        fullscreenBtn.innerHTML = `<i class="fas fa-expand"></i>${isMobile ? '' : ' <span class="d-none d-sm-inline">Fullscreen</span>'}`;
    }
}

// 处理全屏状态变化
function handleFullscreenChange() {
    isFullscreen = !!document.fullscreenElement;
    updateFullscreenButton(isFullscreen);
    if (!isFullscreen && isMobile) {
        // 移动端退出全屏时的特殊处理
        if (screen.orientation && screen.orientation.unlock) {
            screen.orientation.unlock();
        }
    }
    renderAllPages();
}

// 修改toggleFullscreen函数
async function toggleFullscreen() {
    try {
        if (!document.fullscreenElement) {
            const container = document.getElementById('pdf-container');
            if (isMobile && screen.orientation && screen.orientation.lock) {
                try {
                    await screen.orientation.lock('any');
                } catch (e) {
                    console.log('Screen orientation lock failed:', e);
                }
            }
            await container.requestFullscreen();
        } else {
            await document.exitFullscreen();
        }
    } catch (err) {
        console.log('Fullscreen error:', err);
    }
}

// 监听全屏状态变化
document.addEventListener('fullscreenchange', handleFullscreenChange);

// 触摸事件处理
pagesContainer.addEventListener('touchstart', function(e) {
    touchStartX = e.touches[0].clientX;
    touchStartY = e.touches[0].clientY;
}, false);

pagesContainer.addEventListener('touchmove', function(e) {
    if (!touchStartX || !touchStartY) {
        return;
    }
    e.preventDefault(); // 防止页面滚动
}, false);

pagesContainer.addEventListener('touchend', function(e) {
    if (!touchStartX || !touchStartY) {
        return;
    }

    const touchEndX = e.changedTouches[0].clientX;
    const touchEndY = e.changedTouches[0].clientY;

    const deltaX = touchEndX - touchStartX;
    const deltaY = touchEndY - touchStartY;

    // 确保是水平滑动（而不是垂直滑动）
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
        if (deltaX > 0 && currentScrollPage > 1) {
            // 右滑返回上一页
            pagesContainer.scrollTop -= pagesContainer.children[currentScrollPage - 1].offsetHeight;
        } else if (deltaX < 0 && currentScrollPage < pdfDoc.numPages) {
            // 左滑进入下一页
            pagesContainer.scrollTop += pagesContainer.children[currentScrollPage - 1].offsetHeight;
        }
    }

    touchStartX = null;
    touchStartY = null;
}, false);

document.getElementById('fullscreen').addEventListener('click', toggleFullscreen);

// 初始化PDF
pdfjsLib.getDocument('{{ url_for('file.get_pdf', filename=file.file_name) }}').promise.then(function(doc) {
    pdfDoc = doc;
    document.getElementById('page_count').textContent = doc.numPages;
    renderAllPages();
});